package com.mall.shopping.services;


import com.mall.commons.ShoppingCarts;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ProductConverterByHdf;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

//import com.mall.shopping.services.cache.ShoppingCarts;

@SuppressWarnings("all")
@Slf4j
@Service
public class ICartServiceImpl implements ICartService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ProductConverterByHdf productConverterByHdf;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {


        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        try {

            request.requestCheck();

            List<CartProductDto> cartProductDtos = new ArrayList<>();
            List<ShoppingCarts> shoppingCarts = new ArrayList<>();
            RMap<Long, List<ShoppingCarts>> rMap = redissonClient.getMap("shoppingCart");
            if (rMap.containsKey(request.getUserId())) {
                shoppingCarts = rMap.get(request.getUserId());
            }

            for (ShoppingCarts shoppingCart : shoppingCarts) {

                String checked = shoppingCart.getChecked();
                Integer productNum = shoppingCart.getProductNum();
                Long productId = shoppingCart.getProductId();
                CartProductDto cartProductDto = new CartProductDto();
                Item item = itemMapper.selectByPrimaryKey(productId);
                cartProductDto.setChecked(checked);
                cartProductDto.setProductName(item.getTitle());
                cartProductDto.setSalePrice(item.getPrice());
                String image = item.getImage();
                String[] split = image.split(",");
                cartProductDto.setProductImg(split[0]);
                cartProductDto.setLimitNum((long) item.getLimitNum());
                cartProductDto.setProductId(productId);
                cartProductDto.setProductNum(productNum);
                cartProductDtos.add(cartProductDto);
            }

            cartListByIdResponse.setCartProductDtos(cartProductDtos);
            cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            cartListByIdResponse.setMsg(ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
            cartListByIdResponse.setCode(ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode());
        } catch (Exception e) {
            cartListByIdResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return cartListByIdResponse;
    }


    /*
     * @author: ckd
     * @clsss: 添加商品到购物⻋
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            //检查参数
            request.requestCheck();
            List<ShoppingCarts> shoppingCartList = new ArrayList<>();

            ShoppingCarts shoppingCarts = new ShoppingCarts();
            shoppingCarts.setProductId(request.getItemId());
            shoppingCarts.setProductNum(request.getNum());
            shoppingCarts.setChecked("true");
            //redis配置
            //spring中配置中已经有了，作废
//            Config config = new Config();
//            SingleServerConfig serverConfig = config.useSingleServer()
//                    .setAddress("redis://localhost:6379");
//            RedissonClient redissonClient = Redisson.create(config);
            //取出购物车数据
            RMap<Long, List<ShoppingCarts>> rmap = redissonClient.getMap("shoppingCart");

            //判断是否有之前的用户购物车数据
            if (rmap.containsKey(request.getUserId())) {
                List<ShoppingCarts> shoppingCartsList2 = rmap.get(request.getUserId());
                shoppingCartList = new ArrayList<>(shoppingCartsList2);
            }

            //合并购物车，如果有相同的商品则叠加数量
            boolean hasCarts = false;
            for (ShoppingCarts carts : shoppingCartList) {
                if (carts.getProductId().equals(shoppingCarts.getProductId())) {
                    carts.setProductNum(carts.getProductNum() + shoppingCarts.getProductNum());
                    hasCarts = true;
                    break;
                }
            }

            if (!hasCarts) {
                shoppingCartList.add(shoppingCarts);
            }
            System.out.println(shoppingCartList);
            //写回redis
            rmap.put((long) request.getUserId(), shoppingCartList);
            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            addCartResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return addCartResponse;
    }

    /*
     * @author: ckd
     * @clsss: 更新购物⻋的商品数量
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {

        UpdateCartNumResponse updateCartNumResponse = new UpdateCartNumResponse();
        try {
            request.requestCheck();

            //取出购物车数据
            RMap<Long, List<ShoppingCarts>> rmap = redissonClient.getMap("shoppingCart");
            List<ShoppingCarts> shoppingCartList = rmap.get(request.getUserId());

            //更新数据
            for (ShoppingCarts carts : shoppingCartList) {
                if (carts.getProductId().equals(request.getItemId())) {
                    carts.setProductNum(request.getNum());
                    carts.setChecked(request.getChecked());
                }
            }

            //删除数量少于0的购物车商品
            Iterator<ShoppingCarts> iterator = shoppingCartList.iterator();
            while (iterator.hasNext()) {
                ShoppingCarts next = iterator.next();
                if (next.getProductNum() <= 0) {
                    iterator.remove();
                }
            }

            //写回redis
            rmap.put((long) request.getUserId(), shoppingCartList);
            System.out.println(shoppingCartList);

            updateCartNumResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            updateCartNumResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            updateCartNumResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            updateCartNumResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return updateCartNumResponse;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        return null;
    }

    /*
     * @author: ckd
     * @clsss: 删除购物⻋中的商品
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            RMap<Long, List<ShoppingCarts>> rmap = redissonClient.getMap("shoppingCart");
            List<ShoppingCarts> shoppingCartList = rmap.get(request.getUserId());

            //删除对应商品
            Iterator<ShoppingCarts> iterator = shoppingCartList.iterator();
            while (iterator.hasNext()) {
                ShoppingCarts next = iterator.next();
                if (next.getProductId().equals(request.getItemId())) {
                    iterator.remove();
                }
            }

            //写回redis
            rmap.put((long) request.getUserId(), shoppingCartList);
            System.out.println(shoppingCartList);

            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            deleteCartItemResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return deleteCartItemResponse;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne deleteCheckedItemResposne = new DeleteCheckedItemResposne();

        try {
            request.requestCheck();
            RMap<Long, List<ShoppingCarts>> map = redissonClient.getMap("shoppingCart");
            List<ShoppingCarts> shoppingCartList = map.get(request.getUserId());
            Iterator<ShoppingCarts> iterator = shoppingCartList.iterator();
            while (iterator.hasNext()) {
                ShoppingCarts next = iterator.next();
                if (next.getChecked().equals("true")) {
                    iterator.remove();
                }
            }
//            for (ShoppingCarts shoppingCarts : shoppingCartList) {
//
//            }
//            map.remove(request.getUserId());
            map.put((long) request.getUserId(), shoppingCartList);
            deleteCheckedItemResposne.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.info("ShoppingCartServiceImpl#deleteCheckedItem " + e);
            deleteCheckedItemResposne.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return deleteCheckedItemResposne;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
